<script>
import { ImageAPI } from "../apis";
import OrderManager from "../components/OrderManager.vue";
import GlobalUpload from "../components/GlobalUpload.vue";
export default {
  data() {
    return {
      models: [],
      form: {
        model_1_id: null,
        model_2_id: null,
        count: null,
      },
      order: {},
      items: [],
      orderItem: {
        images: [],
      },
      cron: null,
    };
  },
  components: {
    GlobalUpload,
    OrderManager,
  },
  computed: {
    refaceModels() {
      return this.models.filter(
        (model) => model.source === "DFL" || model.source === "TX"
      );
    },
    preview_image_list() {
      const urls = this.orderItem.images.map((image) => image.thumbnail_url);
      return urls;
    },
  },
  async mounted() {
    await this.getModels();
  },
  methods: {
    async getModels() {
      const models = await ImageAPI.getModels();
      this.models = models;
    },
    async addOrderItems() {
      await ImageAPI.createOrderItems({
        order_id: this.order.order_id,
        model_1_id: this.form.model_1_id,
        model_2_id: this.form.model_2_id,
        count: this.form.count,
      });
      await this.selectOrder(this.order);
    },
    async selectOrder(order) {
      const orderItems = await ImageAPI.getOrderItems({
        order_id: order.order_id,
      });
      this.order = order;
      this.items = orderItems;
    },

    // 开关订单项激活状态
    async switchOrderItemActiveStatus(item, index) {
      const new_status = !item.is_active;
      await ImageAPI.updateOrderItem({
        order_item_id: item.order_item_id,
        is_active: new_status,
      });
      this.items[index].is_active = new_status;
      await this.selectOrder(this.order);
    },

    async selectOrderItem(orderItem) {
      this.orderItem = orderItem;
      const that = this;
      const images = await ImageAPI.getImages({
        order_item_id: orderItem.order_item_id,
      });
      this.orderItem.images = images;
      clearInterval(this.cron);
      this.cron = setInterval(async () => {
        that.selectOrder(that.order).then();
        const images = await ImageAPI.getImages({
          order_item_id: orderItem.order_item_id,
        });
        that.orderItem.images = images;
      }, 5000);
    },

    async deleteOrderItem(orderItem) {
      await ImageAPI.deleteOrderItem({
        order_item_id: orderItem.order_item_id,
      });
      await this.getOrderItems();
      const index = this.items.findIndex(
        (item) => item.order_item_id === orderItem.order_item_id
      );
      this.items.splice(index, 1);
      this.orderItem = {
        images: [],
      };
    },

    // 获取订单项，如果有默认项的话，就选默认的
    async getOrderItems() {
      const orderItems = await ImageAPI.getOrderItems({
        order_id: this.order.order_id,
      });
      this.orderItems = orderItems;
      if (orderItems.length > 0) {
        await this.selectOrderItem(orderItems[0]);
      }
    },

    async uploadSuccess() {
      await this.selectOrderItem(this.orderItem);
    },
    async deleteImage(index) {
      const image = this.orderItem.images[index];
      if (!image) return;

      await ImageAPI.deleteImage({
        image_id: image.image_id,
      });
      this.orderItem.images.splice(index, 1);
    },

    getOrderItemStatusType(orderItem) {
      switch (orderItem.status) {
        case "PENDING":
          return "warning";
        case "ING":
          return "success";
        case "OK":
          return "primary";
        default:
          return "";
      }
    },
    getStatus(image) {
      switch (image.status) {
        case "READY":
          return "等待处理";
        case "PENDING":
          return "分割完成";
        case "ING":
          return "云端处理";
        case "OK":
          return "处理完成";
        default:
          return "错误";
      }
    },
    getStatusType(image) {
      switch (image.status) {
        case "READY":
          return "info";
        case "PENDING":
          return "info";
        case "ING":
          return "warning";
        case "ERROR":
          return "danger";
        case "OK":
          return "success";
        default:
          return "info";
      }
    },
  },
};
</script>

<template>
  <el-container style="calc(100vh - 100px); overflow: auto;">
    <global-upload
      :model_1_id="orderItem ? orderItem.model_1_id : ''"
      :model_2_id="orderItem ? orderItem.model_2_id : ''"
      :order_item_id="orderItem ? orderItem.order_item_id : ''"
      @uploaded="uploadSuccess"
    ></global-upload>

    <order-manager @select-order="selectOrder" />
    <el-aside width="300px" style="padding: 5px">
      <el-card>
        <el-form-item label="左边模特">
          <el-select
            v-model="form.model_1_id"
            placeholder="请选择模特（可选）"
            filterable
            remote
            reserve-keyword
            style="width: 100%"
          >
            <el-option
              v-for="model in models"
              :key="model.model_id"
              :label="model.name"
              :value="model.model_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="右边模特">
          <el-select
            v-model="form.model_2_id"
            placeholder="请选择模特（可选）"
            filterable
            remote
            reserve-keyword
            style="width: 100%"
          >
            <el-option
              v-for="model in models"
              :key="model.model_id"
              :label="model.name"
              :value="model.model_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="拍摄件数">
          <el-input-number
            v-model="form.count"
            controls-position="right"
            placeholder="选择件数"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="addOrderItems"
            style="width: 100%"
            :disabled="!order.order_id || !form.count"
          >
            增加订单项
          </el-button>
        </el-form-item>
      </el-card>
      <el-card style="margin-top: 10px">
        <div v-for="oi in items" :key="oi.order_item_id">
          <el-button-group style="display: flex; margin-bottom: 5px">
            <el-button
              style="flex-shrink: 3"
              :type="
                orderItem.order_item_id === oi.order_item_id ? 'primary' : ''
              "
              @click="selectOrderItem(oi)"
            >
              <span style="margin-right: 4px">
                {{ oi.model_1 ? oi.model_1.name + " (L)" : "" }}
              </span>
              <span>
                {{ oi.model_2 ? oi.model_2.name + " (R)" : "" }}
              </span>
            </el-button>
            <el-button
              style="flex: 1"
              :type="
                orderItem.order_item_id === oi.order_item_id ? 'primary' : ''
              "
              @click="selectOrderItem(oi)"
            >
              {{ oi.images.length }}
            </el-button>

            <el-popconfirm
              title="确定删除？"
              @confirm="deleteOrderItem(oi)"
              v-if="!order.is_locked"
            >
              <template #reference>
                <el-button style="flex-shrink: 2"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </el-button-group>
        </div>
      </el-card>
    </el-aside>

    <!-- 图片区 -->
    <el-main width="auto" style="padding: 5px">
      <div class="image-list">
        <div
          v-for="(image, index) of orderItem.images"
          :key="image.image_id"
          style="display: inline-block; padding-right: 8px; padding-bottom: 8px"
        >
          <el-image
            :src="image.thumbnail_url"
            class="image-item"
            hide-on-click-modal
            :preview-src-list="preview_image_list"
            :initial-index="index"
            :infinite="false"
            fit="cover"
          ></el-image>
          <el-button-group style="width: 320px; display: flex">
            <el-button
              :type="getStatusType(image)"
              :disabled="image.status !== 'OK'"
              style="flex: 3"
              >{{ getStatus(image) }}</el-button
            >
            <el-button
              @click="deleteImage(index)"
              v-if="!order.is_locked"
              type="danger"
              style="flex-shrink: 1"
            >
              删除
            </el-button>
          </el-button-group>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<style scoped>
.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, 320px);
  row-gap: 2px;
  column-gap: 2px;
  grid-auto-rows: 520px;
  overflow: auto;
  height: calc(100vh - 70px);
}

.image-item {
  position: relative;
  width: 320px;
  height: 480px;
  border-radius: 10px;
}
</style>
